package com.feng.server.service.impl;

import com.alibaba.fastjson.JSON;
import com.feng.server.entiry.MessageFrame;
import com.feng.server.service.ChatService;
import com.feng.server.service.UserChatSession;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;


public class ChatServiceImpl implements ChatService {
    private UserChatSession userChatSession = new UserChatSessionImpl();

    @Override
    public void singleSend(MessageFrame messageFrame) {
        String to = messageFrame.getTo();
      Channel channel =  userChatSession.getSessionChannel(to);
      // 用户在线,发送消息
        if(channel !=null){
            send(channel,messageFrame);
        }
    }

    @Override
    public void groupSend(MessageFrame message) {

    }

    @Override
    public void saveConnectedSession(Channel channel, MessageFrame message) {
        userChatSession.registerSession(message.getFrom(), channel);
    }

    private void send(Channel channel, MessageFrame messageFrame) {
        String msg = JSON.toJSONString(messageFrame);
        if(msg==null || msg.trim().equals("")){
            return;
        }
        WebSocketFrame webSocketFrame = new TextWebSocketFrame(msg);
        channel.writeAndFlush(webSocketFrame);
    }
}
